package com.feng.study.demo.spring;

import com.feng.study.entity.UserEntity;
import com.feng.study.service.localhost.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

@Service
@Slf4j
public class TransactionalDemo {
    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private UserService userService;

    /**
     * @Transactional在同一个类中的方法之间调用不生效 原因
     *
     * 调用的代理对象。类型：class com.feng.study.demo.spring.TransactionalDemo$$EnhancerBySpringCGLIB$$d5e6b6ee  织入了事务的代理类
     * 类方法之间调用，类型：class com.feng.study.demo.spring.TransactionalDemo  没有织入事务的代理类
     *
     * 可以看出方法之间的调用不走拦截器，没有走到织入的事务代码
     */
    public void testInvalid() {
        System.out.println("类方法之间调用，类型："+this.getClass());
        this.testTransactional();
    }

    /**
     * 声明式事务
     */
    @Transactional(rollbackFor = Exception.class)
    public void testTransactional() {
        //逻辑处理
        System.out.println("事务----------------");
    }

    /**
     * 编程式事务
     */
    public void testTransactionTemplate() {
        UserEntity userEntity1 = new UserEntity().setName("aaaa").setId(1L).setAge(22).setAddress("abc");
        UserEntity userEntity2 = new UserEntity().setName("aaaa1").setId(5L).setAge(22).setAddress("abc");
        System.out.println("事务开始---");
        transactionTemplate.execute(execute -> {
            try {
                userService.updateById(userEntity1);
                userService.save(userEntity2);
            } catch (Exception e) {
                execute.setRollbackOnly();
                log.error("事务执行失败----回滚数据");
            }
            return "ddd";
        });

        System.out.println("结束");
    }
}
